# 根据av号获取cid
import requests
import json
import re
def get_cid(av):
    av = av.strip('av')
    # 就是在pagelist？aid里的
    url = f'https://api.bilibili.com/x/player/pagelist?aid={av}&jsonp=jsonp'
    res = requests.get(url)
    res_text = res.text
    res_dict = json.loads(res_text)# 将字符串转换成字典
    cid = res_dict['data'][0]['cid']
#    print(cid)
    return cid

# 根据cid获取弹幕
def get_dan_mu(cid):
    url = f'https://api.bilibili.com/x/v1/dm/list.so?oid={cid}'
    res = requests.get(url)
    res_xml = res.content.decode('utf-8')
    pattern = re.compile('<d.*?>(.*?)</d>')
    dan_mu_list = pattern.findall(res_xml)
    # print(dan_mu_list)
    return dan_mu_list
# 保存弹幕文件
def save_to_file(dan_mu_list,filename):
    with open(filename, mode='w', encoding='utf-8') as f:
        for one_dan_mu in dan_mu_list:
           f.write(one_dan_mu)
           f.write('\n')

if __name__ == '__main__':
    av = 'av85097036'
    cid = get_cid(av)
    dan = get_dan_mu(cid)
    save_to_file(dan, f'{av}.txt')